package at.codebase.web.util.json;

import java.util.List;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import at.codebase.core.LinkCreator;
import at.codebase.db.entities.EItem;
import at.codebase.db.entities.EUser;
import at.codebase.web.util.json.JsonEncoder.TransferSettings.MailTransfer;

/**
 * @author Daniel Marth <danielmarth@gmx.at>
 */
public class JsonEncoder {

	public static class TransferSettings{
		String userName;
		MailTransfer mailTransfer;
		boolean exportDescription;
		boolean exportItems;
		public static enum MailTransfer {USER_MAIL, EXAMPLE_MAIL}
		public TransferSettings(String userName, MailTransfer mailTransfer, boolean exportDescription,
				boolean exportItems) {
			super();
			this.userName = userName;
			this.mailTransfer = mailTransfer;
			this.exportDescription = exportDescription;
			this.exportItems = exportItems;
		}
		
	}
	
	@SuppressWarnings("unchecked")
	public static JSONObject encodeUser(EUser user, List<EItem> items, TransferSettings transferSettings) {
		JSONObject jObj = new JSONObject();
		if(transferSettings.mailTransfer.equals(MailTransfer.USER_MAIL)){
			jObj.put(JsonKeys.MAIL, user.getMail());	
		}else{
			jObj.put(JsonKeys.MAIL, "nomail@example.org");
		}
		jObj.put(JsonKeys.GOOGLE_USER_ID, user.getGoogleUserId());
		jObj.put(JsonKeys.USERNAME, transferSettings.userName);
		if(transferSettings.exportDescription){
			jObj.put("bio", user.getDescription());
		}
		
		if(transferSettings.exportItems){
			JSONArray jArray = new JSONArray();
			for (EItem item : items) {
				jArray.add(encodeItem(item));
			}
			jObj.put(JsonKeys.ITEMS, jArray);
		}
		return jObj;
	}

	@SuppressWarnings("unchecked")
	private static JSONObject encodeItem(EItem item) {
		JSONObject jObj = new JSONObject();
		jObj.put(JsonKeys.TITLE, item.getTitle());
		jObj.put(JsonKeys.ITEM_DESCRIPTION, item.getDescription());
		JSONObject jSellerObj = new JSONObject();
		jSellerObj.put(JsonKeys.ID, item.getSeller().get().getId().toString());
		jSellerObj.put(JsonKeys.USERNAME, item.getSeller().get().getUsername());
		jObj.put(JsonKeys.SELLER, jSellerObj);
		jObj.put(JsonKeys.PRICE, new Double(item.getPrice()));
		jObj.put(JsonKeys.URL, LinkCreator.absoluteItemLink(item.getId()));
		return jObj;
	}

}
